<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/6/27
 * Time: 11:18
 */

namespace app\api\controller\v1;


use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\Alidayu;
use app\common\lib\IAuth;
use app\common\model\User;

class Login extends Common
{

    /**
     * @return array
     */
    public function save(){
        if (!request()->isPost()){
            return show(config('code.error'), '您没有权限', [], 403);
        }

        $obj = new Aes();

        //接收的数据需要解密
        $param = input('param.');
        if (empty($param['phone'])){
            return show(config('code.error'), '手机不合法', [], 404);
        }
        if (empty($param['code']) && empty($param['password'])){
            //$param['code'] = $obj->decrypt($param['code']);  //实际生产环境中需要加密处理
            return show(config('code.error'), '手机短信验证码不合法', [], 404);
        }

        //判断是否手机验证码方式登录
        if(!empty($param['code'])) {
            //或者 validate() 方式验证
            $code = Alidayu::getInstance()->checkSmsIdentify($param['phone']);
            if ($code != $param['code']) {
                return show(config('code.error'), '手机短信验证码不存在', [], 404);
            }
        }

        $token = IAuth::setAppLoginToken();
        $data = [
            'token' => $token,
            'time_out' => strtotime("+".config('app.login_time_out_day')),
        ];
        //查询这个手机号是否存在
        $user = User::get(['phone' => $param['phone']]);
        if ($user && $user->status == 1){
            //判断是否密码登录方式
            if (!empty($param['password'])){
                if (IAuth::setMdPassword($param['password'],$user->encrypt) != $user->password){
                    return show(config('code.error'), '密码不正确', [], 403);
                }
            }
            //更新的逻辑
            $id =  model('User')->save($data,['phone' => $param['phone']]);
        }else {
            if (!empty($param['code'])) {
                //第一次登录  注册数据
                $data['username'] = 'newsapi-' . $param['phone'];
                $data['phone'] = $param['phone'];
                $data['status'] = 1;

                $id = model('User')->add($data);
            }else{
                return show(config('code.error'), '用户不存在', [], 403);
            }
        }

        if ($id){
            $result = [
                'token' => $obj->encrypt($token."||".$id."||".time()),
            ];
            return show(config('code.success'), 'OK', $result);
        }else{
            return show(config('code.error'), '登录失败', [], 404);
        }
    }

}